#!/usr/bin/python
# -*- coding: <encoding name> -*-
# @Time : 2023/12/8 21:18
# @Author : 菜菜
# @File : f6_one.py
# @software : PyCharm
# !/usr/bin/python
# -*- coding: <encoding name> -*-

import json
from loguru import logger
import requests

from f6zhishu.tools.db import MongoDb
from f6zhishu.tools.enc import generate_aes_key, aes_decrypt, aes_encrypt, rsa_encrypt
from f6zhishu.tools.timestamp_to_time import to_time
from f6zhishu.settings import RSA_PU_KEY

session = requests.session()


def parse_fenlie(text):
    try:
        if json.loads(text)["appPartVoList"][0]["extChoiceVos"] != None:
            return True
        else:
            return False
    except Exception as e:
        return False


class F6():
    def __init__(self):

        self.module_id = None
        self.key_str = None
        self.data_type = None
        self.vin = None
        self.headers = {
            "authority": "data-backend.f6car.cn",
            "accept": "application/json, text/plain, */*",
            "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "cache-control": "no-cache",
            "channel": "110",
            "content-type": "application/json;charset=UTF-8",
            "origin": "https://shop.f6car.cn",
            "pragma": "no-cache",
            "referer": "https://shop.f6car.cn/",
            "sec-ch-ua": "\"Microsoft Edge\";v=\"119\", \"Chromium\";v=\"119\", \"Not?A_Brand\";v=\"24\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-site",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0",
            "x-requested-with": "XMLHttpRequest"
        }
        self.cookies = None
        # self.cookies = {
            # "f6-data-backendSESSIONID": "d0d889d7-c169-4e45-a21d-9f421b032746",
            # "un": "11861816161253482584",
            # "sensorsdata2015jssdkcross": "%7B%22distinct_id%22%3A%2218c438640194eb-017232fd42cab17-26031051-2073600-18c4386401a330%22%2C%22first_id%22%3A%22%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%7D%2C%22%24device_id%22%3A%2218c438640194eb-017232fd42cab17-26031051-2073600-18c4386401a330%22%7D",
            # "erpLanguage": "zh-CN"
        # }
        self.mids = None
        self.key = generate_aes_key()

        self.mongo = MongoDb()

    # 搜索部分的接口
    def search(self):
        # logger.add("my_log.log", level="DEBUG")
        logger.info("正在抓取vin:" + self.vin)

        t = {
            "vin": self.vin,
            "originalVin": "",
            "noNeedCorrectVin": "false"
        }
        url = 'https://data-backend.f6car.cn/f6-data-backend/data/app/reqVinParse'
        data = {
            "param1": rsa_encrypt(RSA_PU_KEY, self.key),
            "param2": aes_encrypt(self.key, json.dumps(t))
        }
        data = json.dumps(data, separators=(',', ':'))
        response = session.post(url, headers=self.headers, data=data, cookies=self.cookies, proxies=self.proxies)
        # print(response.text)

        try:
            data_json: dict = response.json()
            if str(data_json.get('code')) != str(200):
                # print(data_json)
                return data_json
        except Exception as e:
            return {'code': "-1000", 'msg': "程序错误", 'data': e}

        res_data = response.json()['data']
        # 解密操作 并获取mids
        text = aes_decrypt(self.key, res_data)
        # print(text)
        js = json.loads(text)

        # 判断vin是否能够解析
        if js['code'] != '0000':
            return {'code': "-1002", 'msg': "当前vin无法解析，请更换vin"}

        self.mids = js["vehicleList"][0]['mids'].split(',')
        # 对解密数据金星处理并存入数据库

        # 数据库所要的数据
        vehicleList = js["vehicleList"][0]
        # 具体字段
        brandName = vehicleList['brandName']
        vehicleSystem = vehicleList['vehicleSystem']
        year = vehicleList['year']
        exhaustVolume = vehicleList['exhaustVolume']
        transmissionDesc = vehicleList['transmissionDesc']

        # 组成全名
        name = brandName + ' ' + vehicleSystem + ' ' + year + ' ' + exhaustVolume + ' ' + transmissionDesc

        data = {'vin': self.vin, '时间': to_time(), '名称': name}
        # print(data)

        # id_ = 0  # 菜菜测试用的参数

        datas = self.mongo.insert_one(data)
        if datas.get('code') == 1:
            id_ = datas.get('data').get('id')
        else:
            return {'code': 2, 'msg': datas.get('msg'), 'data': None}

        return {'code': 1, 'msg': 'ok', 'id': id_, 'data': data}

    # 分类部分的接口
    def fenlei(self, moduleId, id_, key, data_type):
        """
          moduleId:分类的id
          id_:存入数据库的唯一值
          key:分类名称
          data_type:大分类名称
        """
        e = {
            "channelId": 1,
            "moduleId": moduleId,
            "vin": self.vin,
            "mids": ','.join(map(str, self.mids))
        }
        url = 'https://data-backend.f6car.cn/f6-data-backend/data/reqVin'
        data = {
            "param1": rsa_encrypt(RSA_PU_KEY, self.key),
            "param2": aes_encrypt(self.key, json.dumps(e))
        }
        data = json.dumps(data, separators=(',', ':'))
        response = session.post(url, headers=self.headers, cookies=self.cookies, data=data, proxies=self.proxies)
        # print(response.text)
        try:
            data_json: dict = response.json()
            if data_json.get('code') != 200:
                return data_json

        except Exception as e:
            return {'code': -1000, 'msg': "程序错误", 'data': e}

        res_data = response.json()['data']
        # 解密操作
        text = aes_decrypt(self.key, res_data)
        # 对解密数据金星处理并存入数据库

        # 传给数据库的数据字典
        db_data = {}
        # 如果没有小分类就不需要再次请求
        if parse_fenlie(text):
            db_data = self.fenlei_plus(text)
        else:
            # print(text)

            # 图片视频数据
            try:
                appDatumImageVos = json.loads(text)["appDatumVos"][0]["appDatumDetailVo"][
                    "appDatumImageVos"]  # 可能存在为空 一个数组
            except Exception as e:
                appDatumImageVos = None
            # 不同品牌的数据
            try:
                partCspuVoList = json.loads(text)["appPartVoList"][0]["partCspuVoList"]  # 一个数组
            except Exception as e:
                partCspuVoList = None

            # 清洗数据的逻辑

            ImageVos = []
            if appDatumImageVos != None:
                for item in appDatumImageVos:
                    resCategoryName = item['resCategoryName']
                    resUrl = item['resourceVoList'][0]['resUrl']  # 只找一个图片或者视频

                    ImageVos.append({resCategoryName: resUrl})

            VoList = []
            if partCspuVoList != None:
                for item in partCspuVoList:
                    groupName = item["cspuDetailVos"][0]["attributeValue"]
                    Value = item["cspuDetailVos"][1]["attributeValue"]  # 蓝字部分
                    skuAttrRos = item['skuAttrRos']
                    # 提取关键键值对
                    skuAttrRos = [{"attrName": item["attrName"], "attrValue": item["attrValue"]} for item in skuAttrRos
                                  if "attrName" in item and "attrValue" in item]
                    # skuAttrRos.append({'Value':Value})

                    # 老板要求的数据格式
                    laoban = {
                        "value": Value,
                        "body": skuAttrRos
                    }

                    VoList.append({groupName: laoban})

            res_dict = {
                "图片视频数据": ImageVos,
                "不同品牌的数据": VoList
            }

            db_data['单数据'] = res_dict

        # id_data = self.mongo.insert_convention_one(id_=id_, data={"蓄电池": db_data}, data_type=1)
        # print('插入数据成功', db_data)
        db_data_s = {key: db_data}
        id_data = self.mongo.insert_convention_one(id_=id_, data=db_data_s, data_type=data_type)
        print(db_data_s)
        # 返回数据
        return {'code': 200, 'msg': 'ok', "data": db_data_s}

    # 分类中的小分类需要再次请求
    def fenlei_plus(self, text, id=None):
        response = session.get('https://data-backend.f6car.cn/f6-data-backend/data/module/advertisementList',
                               headers=self.headers,
                               params={"moduleId": self.module_id}, cookies=self.cookies)

        try:
            data_json: dict = response.json()
            if data_json.get('code') != 200:
                return data_json

        except Exception as e:
            return {'code': "-1000", 'msg': "程序错误", 'data': e}

        staId = response.json()['data'][0]["staCategoryId"]

        data = {
            "cStr": "vPf2VAd1VgQGVIn849iDCw==",
            "channelId": 1,
            "moduleId": self.module_id,
            "staCategoryId": staId,  #
            "useless": "De/SfBZAkGvig1YvW4w1+B7uSkQVYFHTcq5dtNTy0tjsaHKv45Dtp03MW+vJdb0X"
        }
        url = 'https://data-backend.f6car.cn/f6-data-backend/data/queryPartListByExtChoice'
        data['cStr'] = json.loads(text)["appPartVoList"][0]["cStr"]
        # 小分类的具体数量
        length = len(json.loads(text)["appPartVoList"][0]["extChoiceVos"])

        xx_array = {}
        for i in range(length):

            # 多数据的车型备注
            beizhu_name = json.loads(text)["appPartVoList"][0]["extChoiceVos"][i]['value']

            data['useless'] = json.loads(text)["appPartVoList"][0]["extChoiceVos"][i]["useless"]
            data_post = json.dumps(data, separators=(',', ':'))
            response = session.post(url, headers=self.headers, cookies=self.cookies, data=data_post)

            try:
                data_json: dict = response.json()
                if data_json.get('code') != 200:
                    return data_json

            except Exception as e:
                return {'code': "-1000", 'msg': "程序错误", 'data': e}

            # print(response.text)
            # 过滤数据并存入数据库

            js = response.json()['data']
            # 图片视频数据
            try:
                appDatumImageVos = js["appDatumVos"][0]["appDatumDetailVo"]["appDatumImageVos"]  # 可能存在为空
            except Exception as e:
                appDatumImageVos = None
            # 不同品牌的数据
            try:
                partCspuVoList = js["appPartVoList"][0]["partCspuVoList"]  # 一个数组
            except Exception as e:
                partCspuVoList = None

            # 清洗数据的逻辑

            ImageVos = []
            if appDatumImageVos != None:
                for item in appDatumImageVos:
                    resCategoryName = item['resCategoryName']
                    resUrl = item['resourceVoList'][0]['resUrl']  # 只找一个图片或者视频

                    ImageVos.append({resCategoryName: resUrl})

            VoList = []
            if partCspuVoList != None:
                for item in partCspuVoList:
                    groupName = item["cspuDetailVos"][0]["attributeValue"]
                    Value = item["cspuDetailVos"][1]["attributeValue"]  # 蓝字部分
                    skuAttrRos = item['skuAttrRos']
                    # 提取关键键值对
                    skuAttrRos = [{"attrName": item["attrName"], "attrValue": item["attrValue"]} for item in
                                  skuAttrRos
                                  if "attrName" in item and "attrValue" in item]
                    # skuAttrRos.append({'Value': Value})

                    # 老板要求的数据格式
                    laoban = {
                        "value": Value,
                        "body": skuAttrRos
                    }

                    VoList.append({groupName: laoban})

            res_dict = {
                "图片视频数据": ImageVos,
                "不同品牌的数据": VoList
            }

            xx_array[beizhu_name] = res_dict

        return xx_array  # 将不同备注的数据以字典的形式返回

    # 右上角详情部分接口
    def detail(self, id_):
        url = 'https://data-backend.f6car.cn/f6-data-backend/data/app/vehicleDetailListToken'
        data = {
            'vin': self.vin,
            'mids': self.mids
        }
        response = session.get(url, headers=self.headers, cookies=self.cookies, params=data, proxies=self.proxies)

        try:
            data_json: dict = response.json()
            if data_json.get('code') != 200:
                return data_json

        except Exception as e:
            return {'code': -1000, 'msg': "程序错误", 'data': e}

        res_data = response.json()['data']

        # 对解密数据进行处理并存入数据库
        # print(res_data)
        vehicles = res_data["vehicles"]  # 一个数组

        # print('插入数据成功', vehicles)
        id_data = self.mongo.insert_convention_one(id_=id_, data=vehicles, data_type="车辆详情")

        return {'code': 110086, 'msg': "ok", 'data': {'车辆详情': vehicles}}

    def mian(self, vin, cookies, module_id, key, data_type):
        self.cookies = cookies

        # print(self.cookies)

        # self.cookies = {
        #     "f6-data-backendSESSIONID": "d266f5f4-6393-4d36-919b-ccb6559152d3",
        #     "un": "11861955597366751327",
        #     "sensorsdata2015jssdkcross": "%7B%22distinct_id%22%3A%2218c731af19d11bc-09d0a9aef36da28-1f525637-1930176-18c731af19eecf%22%2C%22first_id%22%3A%22%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%7D%2C%22%24device_id%22%3A%2218c731af19d11bc-09d0a9aef36da28-1f525637-1930176-18c731af19eecf%22%7D",
        #     "erpLanguage": "zh-CN",
        #     "mobile": "15978527644"
        # }

        self.vin = vin

        ###其他参数
        self.module_id = module_id
        self.key_str = key
        self.data_type = data_type
        ###

        #####
        # proxyHost = "110.42.9.74"  # 代理IP
        # proxyPort = "16247"  # 代理端口
        # proxyUser = "ZVOcL1Tn"  # 代理账户
        # proxyPass = "a47ztkn1"  # 代理密码
        # proxyMeta = f"http://{proxyUser}:{proxyPass}@{proxyHost}:{proxyPort}"
        self.proxies = {
            # "http": proxyMeta,
            # "https": proxyMeta
        }
        ####

        # 测试返回
        # return {
        #     "module_id": module_id
        # }

        id_data = self.search()
        if id_data.get('code') != 1:
            return id_data
        else:
            id_ = id_data.get('id')
            data3 = id_data.get('data')

        data1 = self.detail(id_)
        if data1.get('code') != 110086:
            return data1
        data_dict = data1.get('data')
        # print(data_dict)
        # for key, value in self.zidian.items():
        #     for x, y in value.items():
        data = self.fenlei(module_id, id_, key, data_type)

        if data.get('code') != 200:
            return data
        else:
            data = data.get('data')

        return_data = {'code': 200, 'data': {**data, **data_dict, **data3}}
        if return_data['data'].get('_id'):
            del return_data['data']['_id']
        # print(return_data)
        return return_data


if __name__ == '__main__':
    """"""
    from f6zhishu.app.vin_all_name import get_dict

    # data_dict = get_dict()

    f6 = F6()
    while True:
        # vin = str(input("请输入vin数据："))  # LVSHCFDB4HE337751
        # F6 = F6("LFV2A2156L3519836", zidian)
        # data = f6.mian(get_dict=data_dict, vin=vin)
        f6.mian("LVSHCFDB4HE337751")
